<template>
	<view class="page-container">
		<div style="height: 89vh; overflow-y: auto;">
			<!-- 顶部导航 -->
			<view class="page-header">
				<van-nav-bar title="选择菜单权限" left-arrow @click-left="navigateBack" />
			</view>

			<!-- 主内容区 -->
			<view class="main-content">
				<!-- 说明文字 -->
				<view class="section-description">
					<p>请为角色选择可访问的菜单，必须先选择父级菜单才能选择其子菜单</p>
				</view>

				<!-- 菜单列表 -->
				<view class="menu-list">
					<view class="menu-category" v-for="(category, catIndex) in menuList" :key="category._id">
						<!-- 父级菜单 -->
						<view class="parent-menu">
							<view class="parent-info">
								<!-- 选择区域 -->
								<view class="select-area" @click="toggleParentSelection(category)">
									<van-checkbox v-model="category.checked" :name="category._id"
										class="parent-checkbox" />
									<div class="parent-details">
										<h3 class="parent-name">{{ category.className }}</h3>
										<p class="parent-desc">{{ category.description || '无描述' }}</p>
									</div>
								</view>

								<!-- 展开/折叠按钮 -->
								<view class="expand-btn" @click="toggleExpand(category)"
									v-if="category.children && category.children.length">
									<van-icon name="arrow-down" class="expand-icon"
										:class="{ 'expanded': category.expanded }" />
								</view>
							</view>

							<!-- 子菜单列表 -->
							<view class="children-menu"
								v-if="category.expanded && category.children && category.children.length"
								:style="{ maxHeight: category.expanded ? (category.children.length * 80 + 40 + 'px') : '0' }">
								<view class="children-inner">
									<view class="child-menu-item" v-for="(child, childIndex) in category.children"
										:key="child._id" @click="toggleChildSelection(category, child)" :class="{
		                'first-child': childIndex === 0,
		                'last-child': childIndex === category.children.length - 1
		              }">
										<van-checkbox v-model="child.checked" :name="child._id"
											:disabled="!category.checked" class="child-checkbox" />
										<div class="child-details">
											<h4 class="child-name">{{ child.menuName }}</h4>
											<p class="child-path">{{ child.pathUrl || '无路径' }}</p>
										</div>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 空状态 -->
					<view class="empty-state" v-if="menuList.length === 0">
						<van-empty description="暂无菜单数据" />
					</view>
				</view>
			</view>

		</div>
		<!-- 底部按钮 -->
		<view class="bottom-area">
			<button class="save-btn" @click="saveMenuSelection">
				保存菜单选择
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 菜单列表数据
				menuList: [],
				// 当前编辑的角色ID（确保一定有值，因为只有修改场景）
				roleId: null,
				// 选中的菜单ID树形结构
				selectedMenus: [],
				roleInfo: {}
			};
		},

		async onLoad(options) {
			// 从路由参数获取角色ID，确保存在
			this.roleId = options.roleId;
			if (!this.roleId) {
				this.$showToast("参数错误，无法编辑角色权限");
				// 延迟返回，确保提示信息能显示
				setTimeout(() => {
					this.navigateBack();
				}, 1500);
				return;
			}

			// 加载菜单数据
			await this.loadMenuData();
			// 加载已选菜单
			this.loadSelectedMenus();
		},

		methods: {
			// 返回上一页
			navigateBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 加载菜单数据
			async loadMenuData() {
				try {
					const result = await this.$axios('menuManage', {}, true);
					if (result.code === 200) {
						// 为每个菜单添加选中状态和展开状态
						this.menuList = (result.data || []).map(category => ({
							...category,
							checked: false,
							expanded: false,
							children: (category.children || []).map(child => ({
								...child,
								checked: false
							}))
						}));
					} else {
						this.$showToast('加载菜单失败：' + (result.msg || '未知错误'));
					}
				} catch (error) {
					this.$showToast('加载菜单失败，请重试');
				}
			},

			// 加载已选择的菜单
			async loadSelectedMenus() {
				try {
					const result = await this.$axios('overallSituation', {
						databaseName: 'role',
						state: 'look',
						_id: this.roleId
					}, true);
					console.log(this.roleId, 'this.roleId');
					if (result.code === 200 && result.data && result.data.length > 0) {
						// 确保selectedMenus是数组格式
						this.selectedMenus = result.data[0].menus || [];
						this.roleInfo = result.data[0] || {}
						this.setMenuCheckStates();
					} else {
						// 没有数据时初始化空数组
						this.selectedMenus = [];
						this.$showToast('未找到角色权限数据，将使用默认设置');
					}
				} catch (error) {
					this.$showToast('加载权限失败，请重试');
				}
			},

			// 根据已选菜单设置勾选状态
			setMenuCheckStates() {
				// 防止selectedMenus不是数组导致报错
				if (!Array.isArray(this.selectedMenus)) {
					this.selectedMenus = [];
					return;
				}

				this.selectedMenus.forEach(menu => {
					// 找到对应的父菜单并勾选
					console.log(this.menuList, 'this.menuList');
					const parentIndex = this.menuList.findIndex(item => item._id === menu.parentId);
					if (parentIndex !== -1) {
						this.menuList[parentIndex].checked = true;
						this.menuList[parentIndex].expanded = true;

						// 确保children是数组
						const children = Array.isArray(menu.children) ? menu.children : [];

						// 勾选子菜单
						children.forEach(childId => {
							const childIndex = this.menuList[parentIndex].children.findIndex(
								child => child._id === childId
							);
							if (childIndex !== -1) {
								this.menuList[parentIndex].children[childIndex].checked = true;
							}
						});
					}
				});
			},

			// 切换父菜单选择状态
			toggleParentSelection(category) {
				category.checked = !category.checked;

				// 如果取消选择父菜单，同时取消所有子菜单的选择
				if (!category.checked) {
					(category.children || []).forEach(child => {
						child.checked = false;
					});
				} else {
					// 选中父菜单时自动展开
					category.expanded = true;
				}
			},

			// 切换展开/折叠状态
			toggleExpand(category) {
				// 只有有子菜单时才能展开/折叠
				if (category.children && category.children.length) {
					category.expanded = !category.expanded;
				}
			},

			// 切换子菜单选择状态
			toggleChildSelection(category, child) {
				// 只有父菜单被选中时才能操作子菜单
				if (category.checked) {
					child.checked = !child.checked;
				} else {
					// 提示用户需要先选择父菜单
					this.$showToast('请先选择父级菜单');
				}
			},

			// 收集选中的菜单ID，构建树形结构
			collectSelectedMenus() {
				const selected = [];

				this.menuList.forEach(category => {
					if (category.checked) {
						// 收集选中的子菜单ID
						const selectedChildren = (category.children || [])
							.filter(child => child.checked)
							.map(child => child._id);

						// 添加到树形结构
						selected.push({
							parentId: category._id,
							children: selectedChildren
						});
					}
				});

				return selected;
			},

			// 保存菜单选择（仅修改操作）
			async saveMenuSelection() {
				// 收集选中的菜单
				const menus = this.collectSelectedMenus();

				// 验证角色ID是否存在
				if (!this.roleId) {
					this.$showToast("角色ID不存在，无法保存");
					return;
				}

				try {
					const params = {
						...this.roleInfo,
						state: 'update',
						databaseName: 'role'
					};

					params.menus = menus

					console.log(params, 'params');

					const result = await this.$axios('overallSituation', params);

					if (result.code === 200) {
						this.$showToast('菜单权限修改成功');
						this.navigateBack();
					} else {
						this.$showToast('保存失败：' + (result.msg || '服务器处理错误'));
					}
				} catch (error) {
					this.$showToast('保存失败，请重试');
				}
			}
		}
	};
</script>

<style scoped>
	/* 基础样式 */
	* {
		box-sizing: border-box;
		margin: 0;
		padding: 0;
	}

	.page-container {
		min-height: 100vh;
		background-color: #f9fafb;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
		color: #111827;
		display: flex;
		flex-direction: column;
	}

	/* 页面标题 */
	.page-header {
		background-color: #fff;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}

	/* 主内容区 */
	.main-content {
		flex: 1;
		padding: 24px 16px;
		overflow-y: auto;
	}

	/* 说明文字 */
	.section-description {
		margin-bottom: 24px;
		padding: 16px;
		background-color: #f0f9ff;
		border-radius: 12px;
		border-left: 4px solid #3b82f6;
	}

	.section-description p {
		color: #3b82f6;
		font-size: 14px;
		line-height: 1.5;
	}

	/* 菜单列表 */
	.menu-list {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	/* 菜单分类 */
	.menu-category {
		background-color: #fff;
		border-radius: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
		overflow: hidden;
		transition: box-shadow 0.2s ease;
	}

	.menu-category:hover {
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
	}

	/* 父级菜单 */
	.parent-menu {
		width: 100%;
	}

	.parent-info {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px 20px;
	}

	.select-area {
		display: flex;
		align-items: center;
		flex: 1;
		cursor: pointer;
		transition: background-color 0.2s ease;
		padding: 4px 0;
		border-radius: 8px;
	}

	.select-area:hover {
		background-color: #f8fafc;
	}

	.parent-checkbox {
		margin-right: 16px;
	}

	.parent-details {
		flex: 1;
	}

	.parent-name {
		font-size: 17px;
		font-weight: 600;
		color: #1e293b;
		margin-bottom: 2px;
	}

	.parent-desc {
		font-size: 13px;
		color: #64748b;
	}

	/* 展开/折叠按钮 */
	.expand-btn {
		cursor: pointer;
		padding: 8px;
		margin-left: 8px;
		border-radius: 50%;
		transition: background-color 0.2s ease;
	}

	.expand-btn:hover {
		background-color: #f1f5f9;
	}

	.expand-icon {
		color: #94a3b8;
		transition: transform 0.3s ease;
	}

	.expand-icon.expanded {
		transform: rotate(180deg);
	}

	/* 子菜单列表 */
	.children-menu {
		background-color: #f8fafc;
		border-top: 1px solid #f1f5f9;
		overflow: hidden;
		transition: max-height 0.3s ease, padding 0.3s ease;
	}

	.children-inner {
		padding: 16px 20px;
		display: flex;
		flex-direction: column;
		gap: 10px;
	}

	/* 子菜单项 */
	.child-menu-item {
		display: flex;
		align-items: center;
		padding: 14px 16px;
		border-radius: 12px;
		background-color: #fff;
		cursor: pointer;
		transition: all 0.2s ease;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
	}

	/* 第一个子元素增加顶部间距 */
	.child-menu-item.first-child {
		margin-top: 8px;
	}

	/* 最后一个子元素增加底部间距 */
	.child-menu-item.last-child {
		margin-bottom: 8px;
	}

	.child-menu-item:hover {
		background-color: #f0f9ff;
		transform: translateX(2px);
		box-shadow: 0 2px 5px rgba(59, 130, 246, 0.08);
	}

	.child-checkbox {
		margin-right: 16px;
	}

	/* 禁用状态样式优化 */
	::v-deep .van-checkbox--disabled .van-checkbox__icon {
		opacity: 0.5;
	}

	::v-deep .van-checkbox--disabled+.van-checkbox__label {
		color: #94a3b8;
		opacity: 0.7;
	}

	.child-details {
		flex: 1;
	}

	.child-name {
		font-size: 16px;
		color: #1e293b;
		margin-bottom: 2px;
	}

	.child-path {
		font-size: 12px;
		color: #94a3b8;
		font-family: monospace;
	}

	/* 空状态 */
	.empty-state {
		padding: 60px 20px;
		text-align: center;
	}

	/* 底部按钮区域 */
	.bottom-area {
		padding: 16px;
		background-color: #fff;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
	}

	/* 保存按钮 */
	.save-btn {
		width: 100%;
		height: 48px;
		background-color: #3b82f6;
		color: #fff;
		border: none;
		border-radius: 16px;
		font-size: 16px;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
	}

	.save-btn:hover {
		background-color: #2563eb;
		transform: translateY(-2px);
		box-shadow: 0 6px 16px rgba(59, 130, 246, 0.2);
	}
</style>